# -*- coding: utf-8 -*-
import frappe
from frappe import _

@frappe.whitelist()
def get_accounting_period(company=None):
    """获取会计期间"""
    if not company:
        company = frappe.defaults.get_defaults().get("Company")
    
    if not company:
        frappe.throw(_("请先设置公司"))
    
    # 获取当前会计期间
    accounting_period = frappe.db.sql("""
        SELECT name, start_date, end_date
        FROM `tabAccounting Period`
        WHERE company = %s
        AND docstatus = 1
        AND %s BETWEEN start_date AND end_date
        ORDER BY start_date DESC
        LIMIT 1
    """, (company, frappe.utils.nowdate()), as_dict=True)
    
    return accounting_period[0] if accounting_period else None

@frappe.whitelist()
def get_financial_statements(company, period_start=None, period_end=None):
    """获取财务报表数据"""
    if not period_start or not period_end:
        period = get_accounting_period(company)
        if period:
            period_start = period.start_date
            period_end = period.end_date
        else:
            frappe.throw(_("无法确定会计期间"))
    
    # 获取资产负债表数据
    balance_sheet = frappe.db.sql("""
        SELECT account, account_number, balance
        FROM `tabGL Balance`
        WHERE company = %s
        AND posting_date BETWEEN %s AND %s
        AND is_cancelled = 0
        GROUP BY account, account_number
        ORDER BY account_number
    """, (company, period_start, period_end), as_dict=True)
    
    # 获取损益表数据
    profit_loss = frappe.db.sql("""
        SELECT account, account_number, SUM(debit) as total_debit, SUM(credit) as total_credit
        FROM `tabGL Entry`
        WHERE company = %s
        AND posting_date BETWEEN %s AND %s
        AND is_cancelled = 0
        GROUP BY account, account_number
        ORDER BY account_number
    """, (company, period_start, period_end), as_dict=True)
    
    return {
        "balance_sheet": balance_sheet,
        "profit_loss": profit_loss,
        "period_start": period_start,
        "period_end": period_end
    }